package com.yuesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuesystem.common.BaseContext;
import com.yuesystem.common.CustomException;
import com.yuesystem.entity.SmsLog;
import com.yuesystem.entity.User;
import com.yuesystem.mapper.UserMapper;
import com.yuesystem.service.SmsLogService;
import com.yuesystem.service.UserService;
import com.yuesystem.util.GetRandomName;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;




/**
 * 用户接口实现类.
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  @Autowired
  private SmsLogService smsLogService;
  
  /**
   * 注册账号.
   */
  @Override
  public void register(String phone, String code, String password, String confirmPassword) {
    if (!password.equals(confirmPassword)) {
      log.info("两次输入的密码不一致，请重试！");
      throw new CustomException("两次输入的密码不一致，请重试！");
    }
    LambdaQueryWrapper<SmsLog> queryWrapper1 = new LambdaQueryWrapper<>();
    queryWrapper1.eq(SmsLog::getPhone, phone)
        .eq(SmsLog::getCode, code);
    SmsLog smsLog = smsLogService.getOne(queryWrapper1);
    if (smsLog == null) {
      throw new CustomException("验证码错误");
    }
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(User::getPhone, phone);
    queryWrapper.eq(User::getIsDeleted, 0);
    User one = this.getOne(queryWrapper);
    if (one == null) {
      User user = new User();
      user.setPhone(phone);
      String startName = GetRandomName.getRandomName();
      log.info(startName);
      user.setUserName(startName);
      String img = "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
      user.setImg(img);
      user.setStatus(0);
      user.setEncryptedPassword(password);
      this.save(user);
      log.info("用户注册成功，user：{}", user);
    } else {
      log.info("该用户已存在，请返回登陆页面登录");
      throw new CustomException("该用户已存在，请返回登录页面登录");
    }
  }
  
  /**
   * 登录验证.
   */
  @Override
  public User loginCheck(String phone, String password) {
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(User::getPhone, phone);
    queryWrapper.eq(User::getEncryptedPassword, password);
    queryWrapper.eq(User::getIsDeleted, 0); // 账号未注销
    User one = this.getOne(queryWrapper);
    return one;
  }
  
  /**
   * 根据phone找id.
   */
  @Override
  public Long getByPhone(String phone) {
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(phone != null, User::getPhone, phone);
    User one = this.getOne(queryWrapper);
    
    if (one != null) {
      Long id = one.getId();
      return id;
    }
    return null;
  }
  
  
  /**
   * 根据用户id返回用户基本信息.
   */
  @Override
  public User getUserMassageById(Long id) {
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(User::getId, id);
    User one = this.getOne(queryWrapper);
    return one;
  }
  
  
  /**
   * 修改个人信息.
   */
  @Override
  @Transactional
  public void updateMassageById(User user) {
    // 获取当前用户ID
    Long userId = BaseContext.getCurrentId();
    log.info("我正在修改个人资料，当前用户是：{}", userId);
    LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
    queryWrapper1.eq(User::getId, userId);
    // 找出当前用户，获取他的用户名，身份
    User user1 = this.getOne(queryWrapper1);
    int status = user1.getStatus();
    String userName = user1.getUserName();
    
    user.setId(userId);
    user.setStatus(status);
    if (!user.getUserName().equals(userName)) {
      // 输入了空
      if (user.getUserName().isEmpty()) {
        throw new CustomException("用户名不能为空");
      }
      LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(User::getUserName, user.getUserName());
      queryWrapper.eq(User::getIsDeleted, 0);
      User one = this.getOne(queryWrapper);
      if (one != null) {
        throw new CustomException("用户名已存在");
      }
    }
    this.updateById(user);
    
  }

  /**
   * 忘记密码.
   */
  @Override
  public void forgetPassword(String phone, String code, String newPassword,
                             String confirmNewPassword) {
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(phone != null, User::getPhone, phone);
    queryWrapper.eq(User::getIsDeleted, 0);
    User one = this.getOne(queryWrapper);
    // 判断账号是否存在
    if (one != null) {
      LambdaQueryWrapper<SmsLog> queryWrapper1 = new LambdaQueryWrapper<>();
      queryWrapper1.eq(SmsLog::getPhone, phone)
          .eq(SmsLog::getCode, code);
      SmsLog smsLog = smsLogService.getOne(queryWrapper1);
      if (smsLog == null) {
        throw new CustomException("验证码错误");
      }
      Long id = getByPhone(phone);
      User userOld = this.getById(id);
      if (!newPassword.equals(confirmNewPassword)) {
        log.info("两次输入的密码不一致，请重试！");
        throw new CustomException("两次新密码输入不一致");
      }
      User userNow = this.getById(id);
      userNow.setEncryptedPassword(newPassword);
      this.updateById(userNow);
    } else {
      log.info("账号不存在，请注册");
      throw new CustomException("账号不存在，请注册");
    }
  }
  
  /**
   * 重置密码.
   */
  @Override
  public void resetPassword(String oldPassword, String newPassword, String confirmNewPassword) {
    
    // 获取当前用户ID
    Long id = BaseContext.getCurrentId();
    User userOld = this.getById(id);
    // 判断旧密码是否正确
    if (!oldPassword.equals(userOld.getEncryptedPassword())) {
      log.info("旧密码输入错误！");
      throw new CustomException("旧密码输入错误！");
    }
    // 判断两次新密码输入是否一致
    if (!newPassword.equals(confirmNewPassword)) {
      log.info("两次输入的新密码不一致，请重试！");
      throw new CustomException("两次新密码输入不一致");
    }
    
    userOld.setEncryptedPassword(newPassword);
    this.updateById(userOld);
  }
  
  /**
   * 分页显示用户.
   */
  @Override
  public Page<User> getUsers(int page, int pageSize, String name, String phone, int status) {
    Page<User> pageInfo = new Page<>(page, pageSize);
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.like(!name.isEmpty(), User::getUserName, name)
        .eq(!phone.isEmpty(), User::getPhone, phone)
        .eq(User::getIsDeleted, 0)
        .eq(User::getStatus, status);
    
    this.page(pageInfo, queryWrapper);
    return pageInfo;
  }
  
  /**
   * 升级某个用户为编辑.
   */
  @Override
  public void upgrade1(Long id) {
    User one = this.getById(id);
    one.setStatus(1);
    this.updateById(one);
  }
  
  /**
   * 升级某个用户为客服.
   */
  @Override
  public void upgrade2(Long id) {
    User one = this.getById(id);
    one.setStatus(3);
    this.updateById(one);
  }
  
  
  /**
   * 获得所有客服.
   */
  @Override
  public List<User> getService() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("status", 3);
    List<User> list = this.list(queryWrapper);
    return list;
  }
  
  /**
   * 获得所有管理员.
   */
  @Override
  public List<User> getAdmin() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("status", 2);
    List<User> list = this.list(queryWrapper);
    return list;
  }
  
  /**
   * 获得所有编辑.
   */
  @Override
  public List<User> getEdit() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("status", 1);
    List<User> list = this.list(queryWrapper);
    return list;
  }
}


